package com.itheima.service.impl;

import com.itheima.aop.Log;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileInputStream;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 业务层实现类
 */
@Service
public class DeptServiceImpl implements DeptService {

    //注入Mapper
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;


    /**
     * 查询所有部门信息
     *
     * @return
     */
    @Override
    public List<Dept> list() {
        //直接调用mapper层查询数据
        List<Dept> list = deptMapper.list();
        return list;
    }

    /**
     * 添加部门
     *
     * @param dept
     */
    @Override
    public void add(Dept dept) {
        //补全Dept中的信息（创建时间，更新时间）
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        //添加部门信息
        deptMapper.insert(dept);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public Dept getById(Integer id) {
        return deptMapper.getById(id);
    }

    /**
     * 根据id修改
     *
     * @param dept
     */
    @Override
    public void updateById(Dept dept) {
        //补全更新时间
        dept.setUpdateTime(LocalDateTime.now());

        deptMapper.updateById(dept);
    }

    /**
     * 根据id删除
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)  //开启事务管理
    @SneakyThrows //data No All Builder Sl4j SneakyThrows
    public void deleteById(Integer id) {

        //添加日志操作（放在上门，无论无何，日志添加必须成功）
        DeptLog deptLog = new DeptLog(null, LocalDateTime.now(), "删除" + id + "部门");
        deptLogService.insert(deptLog);

        //删除部门
        deptMapper.deleteById(id);
        // int i = 1 / 0; //模拟ArithmeticException运行期错误
        //new FileInputStream(""); //FileNotFoundException不属于运行期异常
        //删除该部门下的员工
        empMapper.deleteByDeptId(id);

    }
}
